//
//  VC2TextField.swift
//  ChapterAll
//
//  Created by Kevin on 2020/4/21.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit

class VC2TextField: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let tf = UITextField(frame: CGRect(x: 10, y: 100, width: UIScreen.main.bounds.width - 20, height: 20))
        tf.placeholder = "pls input name"
        view.addSubview(tf)
        
        let tf2 = getTextField(ui: tf)
        tf2.borderStyle = .line
        view.addSubview(tf2)
        
        let tf3 = getTextField(ui: tf2)
        tf3.borderStyle = .bezel
        view.addSubview(tf3)
        
        let tf4 = getTextField(ui: tf3)
        tf4.borderStyle = .roundedRect
        tf4.delegate = self
        view.addSubview(tf4)
        
        let tf5 = getTextField(ui: tf4)
        tf5.borderStyle = .none
        view.addSubview(tf5)
        
        let tf6 = getTextField(ui: tf5)
        tf6.borderStyle = .roundedRect
        tf6.leftView = UIImageView(image: UIImage(named: "ic_action_anchor"))
        tf6.leftViewMode = .always
        view.addSubview(tf6)
    }
    
    func getTextField(ui:UITextField) -> UITextField {
        let textfiled = UITextField()
        textfiled.placeholder = "pls input name"
        textfiled.frame = CGRect(x: 10, y: ui.frame.maxY + 20, width: UIScreen.main.bounds.width - 20, height: 50)
        return textfiled
    }
}

extension VC2TextField: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if string.count > 0 {
            print(string)
            let chars:[Character] = ["1","2","3","4","5","6","7","8","9"]
            if !chars.contains(string.first!) {
                print("输入的不是数字")
                return false
            }
            if textField.text!.count + string.count > 11 {
                print("超过11个数字了")
                return false
            }
        }
        return true
    }
}
